package com.misc.tunewsreader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.util.Log;

public class Sync {

	public static List<String> getReadMessages(SharedPreferences prefs) {
		String user = prefs.getString("pref_sync_key", "--NOKEY--");
		if(user.equals("--NOKEY--")) {
			user = java.util.UUID.randomUUID().toString().substring(0, 6);
			Editor edit = prefs.edit();
			edit.putString("pref_sync_key", user);
			edit.commit();
		}
		long last_id = prefs.getLong("sync_last_id", 0);
		List<String> res = new ArrayList<String>();
		if(!prefs.getBoolean("pref_enable_sync", false)) {
			// syncing disabled
			return res;
		}
		
		List<String> response = getSyncList(user, last_id);
		for (String line : response) {
			String[] data = line.split(";");
			if (data.length < 2)
				continue;

			if (data[0].equals("MAX_ID")) {
				Editor editor = prefs.edit();
				editor.putLong("sync_last_id", Long.parseLong(data[1]));
				editor.commit();
			} else {
				res.add(line);
			}
		}
		return res;
	}

	private static List<String> getSyncList(String user, long last_id) {
		List<String> res = new ArrayList<String>();
		HttpClient client = new DefaultHttpClient();
		// q={"timestamp":{$gte:"1350135161"}}
		HttpGet httpGet = new HttpGet(
				"http://misc0110.net/newsreader/get.php?user=" + user + "&ts=" + last_id);
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					res.add(line.trim());
				}
			} else {
				Log.e("Sync", "Failed to download file");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return res;
	}

	public static void setRead(final String user, final String group, final String id,
			final boolean is_read) {

		Log.d("SYNC", "user: " + user + ", msg-id: " + id);
		Runnable send = new Runnable() {
			@Override
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet httpGet = new HttpGet(
						"http://misc0110.net/newsreader/add.php?user=" + user
								+ "&post=" + id.substring(1, id.length() - 1) + "&status="
								+ (is_read ? "1" : "0"));
				try {
					HttpResponse response = client.execute(httpGet);
				} catch (Exception e) {

				}
			}
		};

		Thread sendRead = new Thread(null, send, "SendReadState");
		sendRead.start();
	}

}
